//
//  AppDelegate.m
//  kuaiyi
//
//  Created by ake on 16/5/3.
//  Copyright © 2016年 ake. All rights reserved.
//

#import "AppDelegate.h"
#import "YZMainViewController.h"
#import "YZMenuView.h"
#import "YZPersonalInfoViewController.h"
#import "YZAttDocTableViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
//新浪微博SDK头文件
#import "WeiboSDK.h"
#import "YZMenuViewUnLogin.h"
#import "YZUserLoginController.h"
#import "YZUserRegisterController.h"

static BOOL myLogin;

@interface AppDelegate ()
//导航控制器
@property (nonatomic,strong)UINavigationController* homeNavVC;
//根控制器
@property (nonatomic,strong)YZMainViewController *mainViewController;
//根控制器的 view 嵌套
@property(nonatomic,strong)UIView* layerView;
@property (nonatomic,strong)UIView* homeView;
@property (nonatomic ,assign)BOOL hasLogin;
@property (nonatomic,strong)UIView *currentMenuView;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    UIWindow *window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window = window;
    
    //思路:
    /**
     1, sb (主页 view + 对应的 VC )
     2, 添加侧栏 view
     3, 添加手势
     */
    
    //1,
    UIStoryboard *mainSB = [UIStoryboard storyboardWithName:@"YZMainView" bundle:nil];
    UINavigationController *homeNavVC = [mainSB instantiateInitialViewController];
    self.homeNavVC = homeNavVC;
    [[UINavigationBar appearance] setBarTintColor:YZGreenColor];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    //设置全局导航条的返回按钮
    UIImage *backImage = [[[UIImage imageNamed:@"home_nav_button_back"]
                           imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
                          imageWithAlignmentRectInsets:UIEdgeInsetsMake(0, 0, 11.5, 0)];
    [[UINavigationBar appearance] setBackIndicatorImage:backImage];
    [[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:backImage];
    [[UIBarButtonItem appearance]
     setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
     forBarMetrics:UIBarMetricsDefault];
    
    self.mainViewController = (YZMainViewController*)homeNavVC.topViewController;
    
    //点击 menuBtn 处理
    __weak __typeof(self)weakSelf = self;
    self.mainViewController.menuBtnBlock = ^{
        [weakSelf didSwipe:nil];
    };
   
    //2,添加侧栏
    // 添加分享--初始化SDK并且初始化第三方平台
    [self initializeTheSDK];
    
    //设置主页阴影
    self.homeView = self.mainViewController.view.subviews.firstObject;
    self.homeView.layer.shadowRadius = 8;
    self.homeView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.homeView.layer.shadowOffset = CGSizeMake(-8, 0);
    self.homeView.layer.shadowOpacity = 0.5;
    
    //设置为登录状态,展示正常的侧栏
//    self.hasLogin =! self.hasLogin;
    switch (self.hasLogin) {
        case NO:
        {
            [self unLoginMenu];
            break;
        }
        case YES:
        {
            [self hasLoginMenu];
            break;
        }
            
        default:
            break;
    }
    
    //3,
    //添加向左滑手势
    UISwipeGestureRecognizer *leftSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(didSwipe:)];
    leftSwipe.direction = UISwipeGestureRecognizerDirectionLeft;
    //添加向右滑手势
    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(didSwipe:)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    [self.mainViewController.homeView addGestureRecognizer:leftSwipe];
    [self.mainViewController.homeView addGestureRecognizer:rightSwipe];
    
    //添加menuView 中的登录或注册按钮的监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginOrRegister:) name:@"loginOrRegister" object:nil];
    //添加登录成功事件的监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(finishedLoginShouldDo) name:@"finishedLogin" object:nil];
    //添加注销帐号的监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logOutShouldDo) name:@"logOut" object:nil];

    window.rootViewController = self.homeNavVC;
    [window makeKeyAndVisible];
    
    return YES;
}

#pragma mark - 注销用户处理
-(void)logOutShouldDo{
    [self.currentMenuView removeFromSuperview];
    [self unLoginMenu];
}

#pragma mark - 登录成功事件处理
-(void)finishedLoginShouldDo{
    //登录成功后,需要未登录状态的 menuView , 更改为登录状态的 menuView
    [self.currentMenuView removeFromSuperview];
    [self hasLoginMenu];
}

#pragma mark - 登录或注册按钮点击跳转实现
-(void)loginOrRegister:(NSNotification*)sender{
    //得到所点击的按钮
    UIButton* destBtn = sender.object;
    UIStoryboard *mainViewSB = [UIStoryboard storyboardWithName:@"YZMainView" bundle:nil];
    if([destBtn.titleLabel.text isEqualToString:@"登录"]){
        //加载登录界面
        YZUserLoginController *loginVC = [mainViewSB instantiateViewControllerWithIdentifier:@"passwordLogin"];
        [self.homeNavVC pushViewController:loginVC animated:YES];
        loginVC.title = @"登录";
    }else{
        //加载注册界面
        YZUserRegisterController *registerVC = [mainViewSB instantiateViewControllerWithIdentifier:@"register"];
        [self.homeNavVC pushViewController:registerVC animated:YES];
        registerVC.title = @"注册";
        
    }
    self.hasSwiped = !self.hasSwiped;
}
#pragma mark - (a)添加完成登录的侧栏
-(void)hasLoginMenu{
    YZMenuView *menuView = [[[NSBundle mainBundle]loadNibNamed:@"YZMenuView" owner:nil options:nil]lastObject];
    [self initializeLoginMenuView:menuView];
    [self addMenuView:menuView];
}
#pragma mark - 初始化已登录的menuView 的内部属性
-(void)initializeLoginMenuView:(YZMenuView*)menuView{
    menuView.personalSettingBtnDidClickBlock = ^(){
        //登录后,跳转基本信息页面
        YZPersonalInfoViewController *personVC = [[YZPersonalInfoViewController alloc] init];
        [self.homeNavVC pushViewController:personVC animated:YES];
        self.hasSwiped = !self.hasSwiped;
    };
    menuView.cellDidClickBlock = ^(Class vcClass){
        NSLog(@"%@",vcClass);
        if ([vcClass isSubclassOfClass:[UIButton class]]) {
            [self Share];
        }
        else{
            //menu选项跳转
            [self.homeNavVC pushViewController:[[vcClass alloc]init] animated:YES];
            self.hasSwiped = !self.hasSwiped;
        }
    };
}
#pragma mark - (b)主页添加未登录的侧栏
-(void)unLoginMenu{
    YZMenuViewUnLogin *menuView = [[YZMenuViewUnLogin alloc]initWithFrame:CGRectMake(0, 0, 300, ScreenSize.height)];
    [self addMenuView:menuView];
}
#pragma mark - (c)开始添加侧栏
-(void)addMenuView:(UIView*)menuView{
    self.currentMenuView = menuView;
    [self.mainViewController.view addSubview:menuView];
    [self.mainViewController.view sendSubviewToBack:menuView];
}

//手势 
-(void)didSwipe:(UISwipeGestureRecognizer *)swipe{
    CGRect rightRect = CGRectMake(300, 0,ScreenSize.width, ScreenSize.height);
    CGRect leftRect =[UIScreen mainScreen].bounds;
     //点击menuBtn 的情况
    if(swipe==nil){
        CGRect rect = CGRectNull;
        switch (self.hasSwiped) {
            case NO:
                rect = rightRect;
                break;
            case YES:
                rect = leftRect;
                break;
            default:
                break;
        }
        [self moveToRect:rect];
    }else if(swipe.direction==UISwipeGestureRecognizerDirectionRight&&self.hasSwiped==NO){
        [self moveToRect:rightRect];
        
    }else if (swipe.direction==UISwipeGestureRecognizerDirectionLeft&&self.hasSwiped==YES){
        [self moveToRect:leftRect];
    }
    
    self.hasSwiped = !self.hasSwiped;
    
}

-(void)moveToRect:(CGRect)rect{
    [UIView animateWithDuration:0.5 animations:^{
        self.homeView.frame =rect;
    }];
}


-(void)Share{
    
    //1、创建分享参数
    NSArray* imageArray = @[[UIImage imageNamed:@"Logos.png"]];
    //（注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）
    if (imageArray) {
        
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"快医APP"
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://mob.com"]
                                          title:@"分享标题"
                                           type:SSDKContentTypeAuto];
        //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil //要显示菜单的视图, iPad版中此参数作为弹出菜单的参照视图，只有传这个才可以弹出我们的分享菜单，可以传分享的按钮对象或者自己创建小的view 对象，iPhone可以传nil不会影响
                                 items:nil
                           shareParams:shareParams
                   onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                       
                       switch (state) {
                           case SSDKResponseStateSuccess:
                           {
                               UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                                   message:nil
                                                                                  delegate:nil
                                                                         cancelButtonTitle:@"确定"
                                                                         otherButtonTitles:nil];
                               [alertView show];
                               break;
                           }
                           case SSDKResponseStateFail:
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           default:
                               break;
                       }
                   }
         ];}
}




/// 初始化SDK并且初始化第三方平台
-(void)initializeTheSDK{
    [ShareSDK registerApp:@"iosv1101"
     
          activePlatforms:@[
                            @(SSDKPlatformTypeSinaWeibo)
                            ]
                 onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"568898243"
                                           appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
                                         redirectUri:@"http://www.sharesdk.cn"
                                            authType:SSDKAuthTypeBoth];
                 break;
             default:
                 break;
         }
     }];

}













@end
